package com.utils.jackyun;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.StringUtil;
import com.utils.jackyun.JackyunGoodsStockInRequest.StockInDetailView;
import com.utils.jackyun.JackyunGoodsStockOutRequest.StockOutDetailView;
import com.zbkj.crmeb.category.model.Category;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.MarkupRateTypeEnum;
import com.zbkj.crmeb.store.model.MarkupRate;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.service.MarkupRateService;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductDescriptionService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;

import lombok.extern.slf4j.Slf4j;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class JkyProductUtil {
    @Autowired
    StoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private MarkupRateService markupRateService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private ICategoryMatchService categoryMatchService;

    /**
     * 推送单个货品信息到吉客云(订单仓储用)
     * @author daigb
     * @date:  2022-04-27 18:35
     */
	public Boolean remotePushProductOne(StoreOrderInfoVo info) {
        try {
        	log.info("--------------- 单个货品推送至吉客云, 货品id: {} ---------------", info.getInfo().getProductId());
            // 待出库商品
            List<StockOutDetailView> stockOutDetailViews = new ArrayList<>();
            // 待创建sku
            List<BaseRequestBizData> skus = new ArrayList<>();
            // 待创建价格
            List<BaseRequestBizData> prices = new ArrayList<>();
            // 待入库
            List<StockInDetailView> stockIn = new ArrayList<>();
            // 查询商户费率
            ChannelMerchant channelMerchant = channelMerchantService.getOne(Wrappers.<ChannelMerchant>lambdaQuery()
                    .eq(ChannelMerchant :: getChannelName, "吉客云")
                    );
            // 临时使用该字段存储
            MarkupRate markupRateEntity = markupRateService.getOne(Wrappers.<MarkupRate>lambdaQuery()
                    .eq(MarkupRate::getMerId, channelMerchant.getId())
                    .eq(MarkupRate ::getType, MarkupRateTypeEnum.PLAT_平台加价率.getType())
                    .last("LIMIT 1"));
            BigDecimal markupRate = markupRateEntity.getRatio();
            StoreProduct storeProduct = storeProductService.getById(info.getInfo().getProductId());
            pushProduct(Arrays.asList(storeProduct), markupRate, stockOutDetailViews, skus, prices, stockIn, true, info);
            
            // 批量出库(正常商品和已下架)
            if(CollectionUtils.isNotEmpty(stockOutDetailViews)) {
            	JkyProductUtil.createJkyGoodsStockOut(stockOutDetailViews, "019");
            }
            // 批量创建货品
            String result = JackyunOpenHttpUtils.post("erp.goods.skuimportbatch", "v1.0", skus);
            if(500 == JSONObject.parseObject(result).getInteger("code")) {
            	log.info("--------------- 吉客云创建货品: {}", result);
            }
            // 批量创建sku价格信息
            JkyProductUtil.createJkyGoodsSku(prices);
            // 批量入库
            JkyProductUtil.createJkyGoodsStockIn(stockIn, "019");
            
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return false;
    }
	
    /**
     * 创建吉客云商品
     * @Description:  
     * @author daigb 
     * @param @param products
     * @param @param markupRate
     * @param @throws Exception
     * @return void
     * @throws
     */
    private void pushProduct(List<StoreProduct> products, BigDecimal markupRate, List<StockOutDetailView> stockOutDetailViews, 
    		List<BaseRequestBizData> skus, List<BaseRequestBizData> prices, List<StockInDetailView> stockIn, Boolean isSyOrder, StoreOrderInfoVo info) throws Exception {
        for(StoreProduct product : products) {
            // 组装商品信息
            CategoryMatch categoryMatch = categoryMatchService.getById(product.getCateId());
            Category category = new Category();
            BeanUtils.copyProperties(categoryMatch, category, "type");
            category.setType(categoryMatch.getType().getCode());
            List<StoreProductAttrValue> values = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                    .eq(StoreProductAttrValue :: getProductId, product.getId())
                    );
            Map<String, Object> map = createJkyOriginalSkus(product, values, category, info);
            @SuppressWarnings("unchecked")
            List<BaseRequestBizData> goodsList = (List<BaseRequestBizData>) map.get("goodsList");
            @SuppressWarnings("unchecked")
            List<BaseRequestBizData> jsonStrs = (List<BaseRequestBizData>) map.get("jsonStrs");
            @SuppressWarnings("unchecked")
            List<StockInDetailView> stockInDetailViews = (List<StockInDetailView>) map.get("stockInDetailViews");

            // 待出库
            if(CollectionUtils.isNotEmpty(goodsList)) {
            	JackyunGoodsAddRequest g = (JackyunGoodsAddRequest)goodsList.get(0);
            	List<StockOutDetailView> views = selectOutJkyGoods(g.getGoodsNo());
            	stockOutDetailViews.addAll(views);
            }
            
            skus.addAll(goodsList);
            prices.addAll(jsonStrs);
            stockIn.addAll(stockInDetailViews);
        }
    }
	
    /**
     * 查询分页商品数据
     * @Description:
     * @author daigb
     * @param @param pageNow
     * @param @param pageSize
     * @param @return
     * @param @throws Exception
     * @return InProductResDTO
     * @throws
     */
    public static JkyProductResDTO selectJkyPage(Integer pageNow, Integer pageSize, String goodsNo) throws Exception {
        JkyProductResDTO jkyProductResDTO = null;
        try {
            JackyunGoodsRequest jackyunGoodsRequest = new JackyunGoodsRequest();
            jackyunGoodsRequest.setPageIndex(pageNow);
            jackyunGoodsRequest.setPageSize(pageSize);
            if(StringUtil.isNotEmpty(goodsNo)) {
                jackyunGoodsRequest.setGoodsNo(goodsNo);
            }
            String result = JackyunOpenHttpUtils.post("erp.storage.goodslist", "v1.0", jackyunGoodsRequest);

            ObjectMapper mapper = new ObjectMapper();
            jkyProductResDTO = mapper.readValue(result, JkyProductResDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jkyProductResDTO;
    }

    /**
     * 创建基于速云原生的吉客云商品资料
     * @author daigb
     * @date:  2022-04-28 10:21
     */
    public Map<String, Object> createJkyOriginalSkus(StoreProduct product, List<StoreProductAttrValue> values, Category category, StoreOrderInfoVo info) throws Exception {
    	Map<String, Object> map = null;
    	try {
    		map = new HashMap<>();
    		List<BaseRequestBizData> goodsList = new ArrayList<>();
    		List<BaseRequestBizData> jsonStrs = new ArrayList<BaseRequestBizData>();
    		List<JackyunGoodsStockInRequest.StockInDetailView> stockInDetailViews = new ArrayList<>();
    		JSONArray sliderImage = JSONArray.parseArray(product.getSliderImage());
    		// 查询货品skuid
    		String keyword = product.getKeyword().replaceAll(" ", "-");
    		JkyProductResDTO jkyProductResDTO = selectJkyPage(0, 200, keyword + "-" + product.getId());
    		// 订单中规格是否存在
    		boolean orderInfoStatus = false;
    		String orderSourceSkuId = info.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
    		// 组装吉客云商品信息
    		for(int i=0; i<values.size(); i++) {
    			if(!orderInfoStatus && orderSourceSkuId.equals(values.get(i).getSourceSkuId())) {
    				orderInfoStatus = true;
    			}
    			// 构建商品和sku信息
    			buildJkyGoods(keyword, product, category, values.get(i), i, sliderImage, jkyProductResDTO, goodsList, jsonStrs, stockInDetailViews);
    		}
    		// 单独添加订单规格
    		if(!orderInfoStatus) {
    			StoreProductAttrValue value = info.getInfo().getProductInfo().getAttrInfo();
    			buildJkyGoods(keyword, product, category, value, 99, sliderImage, jkyProductResDTO, goodsList, jsonStrs, stockInDetailViews);
    		}
    		
    		map.put("goodsList", goodsList);
    		map.put("jsonStrs", jsonStrs);
    		map.put("stockInDetailViews", stockInDetailViews);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	
    	return map;
    }
    
    /**
     * 吉客云商品构建
     * @author daigb
     * @date:  2022-04-29 11:46
     */
    private void buildJkyGoods(String keyword, StoreProduct product, Category category, StoreProductAttrValue value, Integer i, JSONArray sliderImage,
    		JkyProductResDTO jkyProductResDTO, List<BaseRequestBizData> goodsList, List<BaseRequestBizData> jsonStrs, List<JackyunGoodsStockInRequest.StockInDetailView> stockInDetailViews) {
		// 商品和sku信息
		JackyunGoodsAddRequest goods = new JackyunGoodsAddRequest();
		goods.setGoodsName(product.getStoreName());
		goods.setGoodsNo(keyword + "-" + product.getId().toString());
		goods.setGoodsAlias(keyword);
		goods.setCateCode(product.getCateId().toString());
		goods.setCateName(category.getName());
		goods.setBrandName(product.getBrandName());
		goods.setUnitName(product.getUnitName());
		if(!value.getSuk().contains(";") && !StringUtil.isEmpty(product.getColorCode())) {
			goods.setSkuName(i + product.getColorCode() + "," + value.getSuk());
		} else {
			goods.setSkuName(i + value.getSuk().replace(";", ","));
		}
		goods.setOutSkuCode(value.getSourceSkuId());
		goods.setSkuBarcode(value.getSourceSkuId());
		goods.setSkuNo(value.getSourceSkuId());
		goods.setMainBarcode(keyword); // 公码
		goods.setMainGoodsUrl(product.getImage());
		goods.setSkuImageUrl(value.getImage());
		if(null != sliderImage) {
			if(4 < sliderImage.size()) {
				goods.setTopGoodsUrl(sliderImage.getString(1));
				goods.setBelowGoodsUrl(sliderImage.getString(2));
				goods.setLeftGoodsUrl(sliderImage.getString(3));
				goods.setRightGoodsUrl(sliderImage.getString(4));
			} else {
				for(int z=0; z<sliderImage.size(); z++) {
					if(z == 0) {
						goods.setTopGoodsUrl(sliderImage.getString(z));
					} else if(z == 1) {
						goods.setBelowGoodsUrl(sliderImage.getString(z));
					} else if(z == 2) {
						goods.setLeftGoodsUrl(sliderImage.getString(z));
					} else if(z == 3) {
						goods.setRightGoodsUrl(sliderImage.getString(z));
					}
				}
			}
		}
		
		goods.setDescript("");
		goodsList.add(goods);
		
		// 价格
		BigDecimal price = value.getPrice();
		JackyunGoodsSkuAddRequest skuPrice = new JackyunGoodsSkuAddRequest();
		skuPrice.setSkuName(goods.getSkuName());
		skuPrice.setRetailPrice(price);
		skuPrice.setSkuWeight(value.getOtPrice()); // 原价往重量上赋值
		skuPrice.setSkuBarcode(value.getSourceSkuId());
		// 匹配吉客云skuId
		List<JkyProductResDTO.Goods> jkyGoodsList = jkyProductResDTO.getResult().getDataResult().getGoods();
		for(JkyProductResDTO.Goods g : jkyGoodsList) {
			if(null == g.getSkuCode()) {
				continue;
			}
			if(g.getSkuCode().equals(goods.getSkuNo())) {
				skuPrice.setSkuId(g.getSkuId());
				break;
			}
		}
		if(StringUtil.isEmpty(skuPrice.getSkuId())) {
			//todo 占位
//			skuPrice.setSkuId(value.getId().toString());
		}
		jsonStrs.add(skuPrice);
		
		// 库存
		JackyunGoodsStockInRequest.StockInDetailView stockInDetailView = new JackyunGoodsStockInRequest.StockInDetailView();
		stockInDetailView.setSkuBarcode(value.getSourceSkuId());
		stockInDetailView.setRelDetailId(0);
//		stockInDetailView.setSkuCount(new BigDecimal(value.getStock()));
		// 默认给十个库存
		stockInDetailView.setSkuCount(BigDecimal.TEN);
		stockInDetailView.setIsCertified("1");
		stockInDetailViews.add(stockInDetailView);
    }

    /**
     * 生成出库单
     * @Description:
     * @author daigb
     * @param @throws Exception
     * @return void
     * @throws
     */
    public static void createJkyGoodsStockOut(List<JackyunGoodsStockOutRequest.StockOutDetailView> stockOutDetailViews, String warehouseCode) throws Exception {
        JackyunGoodsStockOutRequest stock = new JackyunGoodsStockOutRequest();
        stock.setOutWarehouseCode(warehouseCode);
        stock.setOutType(204);
        Long l = System.currentTimeMillis();
        stock.setRelDataId(l + "");
        stock.setApplyDepartName("daigb");
        stock.setApplyDate(new Date());
        stock.setOperator("daigb");
        stock.setSource("OPEN");

        stock.setStockOutDetailViews(stockOutDetailViews);

        String result = JackyunOpenHttpUtils.post("erp.stock.createandstockout", "v1.0", stock);
        //if(500 == JSONObject.parseObject(result).getInteger("code")) {
            log.info("--------------- 吉客云出库: {}", result);
       // }
    }

    /**
     * 批量创建商品价格
     * @Description:
     * @author daigb
     * @param @param goodsNo
     * @param @param skuBarcode
     * @param @throws Exception
     * @return void
     * @throws
     */
    public static void createJkyGoodsSku(List<BaseRequestBizData> jsonStrs) throws Exception {
        String result = JackyunOpenHttpUtils.post("erp.goodsku.updatebyskubarcode", "v1.0", jsonStrs);
        //if(500 == JSONObject.parseObject(result).getInteger("code")) {
            log.info("--------------- 吉客云创建sku价格: {}", result);
        //}
    }

    /**
     * 生成入库单
     * @Description:
     * @author daigb
     * @param @throws Exception
     * @return void
     * @throws
     */
    public static void createJkyGoodsStockIn(List<JackyunGoodsStockInRequest.StockInDetailView> stockInDetailViews, String warehouseCode) throws Exception {
        JackyunGoodsStockInRequest stock = new JackyunGoodsStockInRequest();
        stock.setApplyDepartCode("CP003");
        stock.setApplyCompanyCode("0001");
        stock.setInWarehouseCode(warehouseCode);
        stock.setInType(104);
        stock.setRelDataId(System.currentTimeMillis() + "");
        stock.setApplyUserName("daigb");
        stock.setApplyDate(new Date());
        stock.setOperator("daigb");
        stock.setSource("OPEN");
        stock.setLogisticNo("SF888888888888");
        stock.setStockInDetailViews(stockInDetailViews);

        String result = JackyunOpenHttpUtils.post("erp.stock.createandstockin", "v1.0", stock);
        //if(500 == JSONObject.parseObject(result).getInteger("code")) {
            log.info("--------------- 吉客云入库: {}", result);
        //}
    }

    /**
     * @return
     * 查询待出库商品
     * @Description:
     * @author daigb
     * @param @param product
     * @param @param values
     * @param @param category
     * @param @param markupRate
     * @param @throws Exception
     * @return void
     * @throws
     */
    public static List<JackyunGoodsStockOutRequest.StockOutDetailView> selectOutJkyGoods(String id) throws Exception {
        // 先查询商品sku信息, 将库存出库
        List<JackyunGoodsStockOutRequest.StockOutDetailView> stockOutDetailViews = null;
        try {
            stockOutDetailViews = new ArrayList<>();
            List<JkyProductSkuResDTO.GoodsStockQuantity> goodsStockQuantitys = getJkySkus(id);
            for(JkyProductSkuResDTO.GoodsStockQuantity stockQuantity : goodsStockQuantitys) {
                if(Integer.parseInt(stockQuantity.getCurrentQuantity()) > 0) {
                    JackyunGoodsStockOutRequest.StockOutDetailView stockOutDetailView = new JackyunGoodsStockOutRequest.StockOutDetailView();
                    stockOutDetailView.setSkuBarcode(stockQuantity.getSkuBarcode());
                    stockOutDetailView.setRelDetailId(0);
                    stockOutDetailView.setSkuCount(new BigDecimal(stockQuantity.getCurrentQuantity()));
                    stockOutDetailView.setIsCertified("1");
                    stockOutDetailViews.add(stockOutDetailView);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return stockOutDetailViews;
    }

    /**
     * @throws Exception
     * 单商品库存查询
     * @Description:
     * @author daigb
     * @param @param goodsNo
     * @param @return
     * @param @throws Exception
     * @return JkyProductSkuResDTO
     * @throws
     */
    public static List<JkyProductSkuResDTO.GoodsStockQuantity> getJkySkus(String goodsNo) throws Exception {
        List<JkyProductSkuResDTO.GoodsStockQuantity> goodsStockQuantitys = null;
        try {
            JackyunGoodsRequest jackyunGoodsRequest = new JackyunGoodsRequest();
            jackyunGoodsRequest.setPageIndex(0);
            jackyunGoodsRequest.setPageSize(200);
            jackyunGoodsRequest.setWarehouseCode("019");
            jackyunGoodsRequest.setGoodsNo(goodsNo);
            String result = JackyunOpenHttpUtils.post("erp.stockquantity.get", "v1.0", jackyunGoodsRequest);
            ObjectMapper mapper = new ObjectMapper();
            JkyProductSkuResDTO jkyProductSkuResDTO = mapper.readValue(result, JkyProductSkuResDTO.class);
            goodsStockQuantitys = jkyProductSkuResDTO.getResult().getDataResult().getGoodsStockQuantity();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return goodsStockQuantitys;
    }

}
